<?php
/**
 * OA工作汇报模型
 */

declare (strict_types = 1);

namespace app\model\oa;

use think\Model;
use think\facade\Db;

class Work extends Model
{
    // 设置表名
    protected $name = 'work';
    
    // 设置主键
    protected $pk = 'id';
    
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';
    
    // 设置字段信息
    protected $schema = [
        'id'           => 'int',
        'admin_id'     => 'int',
        'types'        => 'int',
        'to_uids'      => 'string',
        'works'        => 'string',
        'file_ids'     => 'string',
        'start_date'   => 'int',
        'end_date'     => 'int',
        'create_time'  => 'int',
        'update_time'  => 'int',
        'delete_time'  => 'int',
    ];

    /**
     * 获取发送的工作汇报列表
     */
    public function getSendList(int $adminId, array $params = [], int $page = 1, int $limit = 10): array
    {
        $query = $this->where('admin_id', $adminId)
                     ->where('delete_time', 0);

        // 按类型筛选
        if (!empty($params['types'])) {
            $query->where('types', $params['types']);
        }

        // 按时间检索
        if (!empty($params['date_range'])) {
            $dateRange = explode('~', $params['date_range']);
            $query->whereBetween('start_date', [
                strtotime(urldecode($dateRange[0])), 
                strtotime(urldecode($dateRange[1] . ' 23:59:59'))
            ]);
        }

        $total = $query->count();

        $list = $query->field('id,types,works,file_ids,start_date,end_date,create_time')
                     ->order('create_time', 'desc')
                     ->page($page, $limit)
                     ->select()
                     ->toArray();

        // 处理数据格式
        foreach ($list as &$item) {
            $item = $this->formatWorkItem($item);
        }

        return [
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ];
    }

    /**
     * 获取接收的工作汇报列表
     */
    public function getReceiveList(int $toUid, array $params = [], int $page = 1, int $limit = 10): array
    {
        $query = Db::name('oa_work_record')
                  ->alias('a')
                  ->join('oa_work w', 'a.work_id = w.id', 'left')
                  ->where('a.to_uid', $toUid)
                  ->where('a.delete_time', 0);

        // 按阅读状态筛选
        if (!empty($params['read_status'])) {
            if ($params['read_status'] == 1) {
                $query->where('a.read_time', 0);
            } else {
                $query->where('a.read_time', '>', 0);
            }
        }

        // 按类型筛选
        if (!empty($params['types'])) {
            $query->where('w.types', $params['types']);
        }

        // 按时间检索
        if (!empty($params['date_range'])) {
            $dateRange = explode('~', $params['date_range']);
            $query->whereBetween('a.send_time', [
                strtotime(urldecode($dateRange[0])), 
                strtotime(urldecode($dateRange[1] . ' 23:59:59'))
            ]);
        }

        $total = $query->count();

        $list = $query->field('a.id,a.work_id,a.from_uid,a.send_time,a.read_time,w.types,w.works,w.file_ids,w.start_date,w.end_date')
                     ->order('a.send_time', 'desc')
                     ->page($page, $limit)
                     ->select()
                     ->toArray();

        // 处理数据格式
        foreach ($list as &$item) {
            $item = $this->formatReceiveItem($item);
        }

        return [
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ];
    }

    /**
     * 获取工作汇报详情
     */
    public function getDetail(int $id, string $type = 'send', int $userId = 0): ?array
    {
        if ($type === 'send') {
            $work = $this->where('id', $id)
                        ->where('delete_time', 0)
                        ->find();
            
            if (!$work) {
                return null;
            }

            // 检查权限
            if ($userId && $work['admin_id'] != $userId) {
                return null;
            }

            $work = $work->toArray();
            return $this->formatWorkDetail($work);
        } else {
            // 接收的汇报详情
            $work = Db::name('oa_work_record')
                     ->alias('a')
                     ->join('oa_work w', 'a.work_id = w.id', 'left')
                     ->where('a.id', $id)
                     ->where('a.delete_time', 0)
                     ->find();

            if (!$work) {
                return null;
            }

            // 检查权限
            if ($userId && $work['to_uid'] != $userId) {
                return null;
            }

            $work = $work->toArray();
            return $this->formatReceiveDetail($work);
        }
    }

    /**
     * 格式化工作项数据
     */
    private function formatWorkItem(array $item): array
    {
        if ($item['start_date'] > 0) {
            $item['start_date'] = date('Y-m-d', $item['start_date']);
        }
        if ($item['end_date'] > 0) {
            $item['end_date'] = date('Y-m-d', $item['end_date']);
        }
        $item['create_time'] = date('Y-m-d H:i', $item['create_time']);
        $item['files'] = Db::name('file')->whereIn('id', $item['file_ids'])->count();
        return $item;
    }

    /**
     * 格式化接收项数据
     */
    private function formatReceiveItem(array $item): array
    {
        $item['send_time'] = empty($item['send_time']) ? '-' : date('Y-m-d H:i:s', $item['send_time']);
        $item['from_name'] = Db::name('admin')->where('id', $item['from_uid'])->value('name');
        
        if ($item['start_date'] > 0) {
            $item['start_date'] = date('Y-m-d', $item['start_date']);
        }
        if ($item['end_date'] > 0) {
            $item['end_date'] = date('Y-m-d', $item['end_date']);
        }
        
        $item['files'] = Db::name('file')->whereIn('id', $item['file_ids'])->count();
        return $item;
    }

    /**
     * 格式化工作详情
     */
    private function formatWorkDetail(array $work): array
    {
        if ($work['types'] > 1) {
            $work['range_date'] = date('Y-m-d', $work['start_date']) . ' ~ ' . date('Y-m-d', $work['end_date']);
        } else {
            $work['range_date'] = date('Y-m-d', $work['start_date']);
        }

        $to_uids = explode(',', $work['to_uids']);
        $to_unames = Db::name('admin')->whereIn('id', $to_uids)->column('name');
        $work['to_unames'] = implode(',', $to_unames);
        $work['file_array'] = Db::name('file')->whereIn('id', $work['file_ids'])->select()->toArray();
        $work['create_time'] = date('Y-m-d H:i', $work['create_time']);
        return $work;
    }

    /**
     * 格式化接收详情
     */
    private function formatReceiveDetail(array $work): array
    {
        $work['send_time'] = empty($work['send_time']) ? '-' : date('Y-m-d H:i:s', $work['send_time']);
        $work['from_name'] = Db::name('admin')->where('id', $work['from_uid'])->value('name');
        
        if ($work['start_date'] > 0) {
            $work['start_date'] = date('Y-m-d', $work['start_date']);
        }
        if ($work['end_date'] > 0) {
            $work['end_date'] = date('Y-m-d', $work['end_date']);
        }
        
        $work['file_array'] = Db::name('file')->whereIn('id', $work['file_ids'])->select()->toArray();
        return $work;
    }
}